<template>
  <Drawer :title="getTitle">
    <BaseForm />
  </Drawer>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'EditDrawer',
});
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { dictdataSave, dictdataEdit } from '../data/api';
import { drawerFormSchema, DictId } from '../data/options';
import { message } from 'ant-design-vue';
import { useThrottleFn } from '@vueuse/core';

const emit = defineEmits(['success']);

// 弹窗标题
const info: any = ref({});
const getTitle = computed(() => {
  return `${info.value?.dictDataId ? '编辑' : '新增'}字典项`;
});

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/3',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => formApi.submitForm(),
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      info.value = drawerApi.getData();
      console.log(info.value);
      info.value.dictId = DictId.value || undefined;
      formApi.setValues({ ...info.value });
    }
  },
});

//  提交
const onSubmit = useThrottleFn(async (values: Record<string, any>) => {
  console.log(values);
  const { valid } = await formApi.validate();
  if (!valid) return;
  let query = info.value.dictDataId ? dictdataEdit : dictdataSave;
  let res: any = await query({ ...values });
  console.log(res);
  message.success(res.message);
  drawerApi.close();
  emit('success');
}, 1000);

// 表单
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-0 pr-4 pt-4 pb-4',
  schema: drawerFormSchema,
  handleSubmit: onSubmit,
  // 所有表单项
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
});
</script>
<style lang="scss" scoped></style>
